package com.sxd.bill.rela.extractor;

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import com.sxd.bill.common.enums.LabelNameEnum;
import com.sxd.bill.common.item.LabelItem;
import com.sxd.bill.common.item.TextLabelItem;
import com.sxd.bill.rela.item.CoreRelationItem;

public class IntegrateExtractor implements Extractable {
    protected LabelNameEnum multiValLabel;

    public IntegrateExtractor(LabelNameEnum multiValLabel) {
        this.multiValLabel = multiValLabel;
    }

    public IntegrateExtractor() {
        this.multiValLabel = null;
    }

    public LabelNameEnum getMultiValLabel() {
        return multiValLabel;
    }

    protected TextLabelItem preprocessing(TextLabelItem textLabelItem) {
        return textLabelItem;
    }

    protected boolean checkCondition(TextLabelItem textLabelItem) {
        // 取出标签名称
        List<LabelNameEnum> labelNames = textLabelItem.getLabelItems()
                .stream()
                .map(item -> item.getLabelName())
                .collect(Collectors.toList());
        // 统计标签名称出现的次数
        Map<LabelNameEnum, Integer> counter = new HashMap<>();
        for (LabelNameEnum labelName : labelNames) {
            counter.put(labelName, counter.getOrDefault(labelName, 0) + 1);
        }
        // 获取出现次数大于1的标签名称
        Map<LabelNameEnum, Integer> dumplcates = new HashMap<>();
        for (Map.Entry<LabelNameEnum, Integer> entry : counter.entrySet()) {
            if (entry.getValue() > 1) {
                dumplcates.put(entry.getKey(), entry.getValue());
            }
        }
        // 判断
        if (multiValLabel == null) {
            return dumplcates.size() == 0;
        } else if (dumplcates.size() == 1 && dumplcates.containsKey(multiValLabel)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<CoreRelationItem> extract(TextLabelItem textLabelItem) {
        List<CoreRelationItem> results = new ArrayList<>();
        // 检查是否满足条件
        if (!checkCondition(textLabelItem)) {
            return results;
        }
        // 预处理
        TextLabelItem newTextLabelItem = preprocessing(textLabelItem);
        // 组合要素(标签实体)
        List<LabelItem> labelItems = newTextLabelItem.getLabelItems();
        CoreRelationItem relaItem = new CoreRelationItem();
        for (LabelItem labelItem : labelItems) {
            relaItem.update(labelItem.getLabelName(), labelItem.getLabelEntity());
        }
        relaItem.setExtractingText(newTextLabelItem.getText());
        results.add(relaItem);
        return results;
    }

    public String toString() {
        return String.format("%s(multiValLabel=%s)", this.getClass().getSimpleName(), multiValLabel);
    }
}
